package com.meeting.y.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.swagger.annotation.ActionApi;
import com.jfinal.swagger.annotation.Api;
import com.jfinal.swagger.annotation.Param;
import com.jfinal.swagger.annotation.Params;
import com.jfinal.upload.UploadFile;
import com.meeting.y.model.AuthUser;
import com.meeting.y.model.MeetingsMeeting;
import com.meeting.y.util.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Time;
import java.util.*;

@Api(remark="YmeetingExportController，导出资料", sort=10)
public class YmeetingExportController extends Controller {

    private static final Logger logger = LoggerFactory.getLogger(YmeetingController.class);

    @ActionApi(remark = "导出辅助课时表/薪资条")
    @Params({
            @Param(name = "teacherid", remark = "老师id,默认方方", defaultValue = "1741", dataType = "integer", required = true),
            @Param(name = "classfee", remark = "课时费", defaultValue = "550.d", dataType = "integer", required = true),
            @Param(name = "year", remark = "年", defaultValue = "2020", dataType = "integer", required = true),
            @Param(name = "month", remark = "月", defaultValue = "1", dataType = "integer", required = true),
            @Param(name = "modeltype", remark = "资料类型，1 课时表，2薪资条", defaultValue = "1", dataType = "integer", required = true)
    })
    public void index(){

        Integer _month = getParaToInt("month",0);
        Integer current = getParaToInt("classrelaid",0);
        Integer _modeltype = getParaToInt("modeltype",0);
        if(current <= 0) {
            current = NumberTool.safeToInteger(this.getRequest().getAttribute("relauserid"),0);
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,_month);

        //获取 老师，年月，模板类型
        String _tearchname = "方方";
        Integer _teacherid = 1741;
        Double classfee = 1.d;

        Integer year = 2020;
        Integer month = 1;
        Integer modeltype = 1;//1 课时表，2薪资条

        if(current>0){
            AuthUser authUser = AuthUser.dao.findById(current);
            _tearchname = authUser.getFirstName();
            _teacherid = current;
            classfee = authUser.getClassfee()!=null? authUser.getClassfee().doubleValue():classfee;
        }
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        if(_modeltype>0){
            modeltype = _modeltype;
        }

        Calendar date = Calendar.getInstance();
        date.set(Calendar.YEAR, year);//设为当前月的1号
        date.set(Calendar.MONTH, month-1);//加一个月，变为下月的1号
        date.set(Calendar.DAY_OF_MONTH, 1);//减去一天，变为当月最后一天
        TimeUtil.setTimeZone(date);
        Date startdate = date.getTime();
        date.add(Calendar.MONTH,1);
        Date enddate = date.getTime();

        //获取所有课程
        List<Record> listclass = MeetingsMeeting.dao.findMeetingsForExport(_teacherid,startdate,enddate);

        Map<String,String> param = new HashMap<>();
        param.put("tearchname",_tearchname);
        param.put("year",year+"");
        param.put("month",month+"");
        param.put("classfee",classfee+"");

        String _file = "";
        //处理导出 课时表
        if(modeltype == 1){

            Record totalResult = MeetingsMeeting.dao.countMeetings(startdate,enddate,_teacherid);
            _file = exportClassExcel(listclass,param,totalResult);
//      薪资条
        }else if(modeltype == 2) {
            _file = exportPayExcel(listclass,param);
        }
        renderFile(new File(_file));
    }

    public String exportClassExcel(List<Record> listclass,Map<String,String> param,Record totalResult){
        String _filename = "XXYYMM月时数表---未核对_TT.xlsx";

        String _tearchname = param.get("tearchname");
        String year = param.get("year");
        String month = param.get("month");
        Double classfee = NumberTool.safeToDouble(param.get("classfee"),0.d);

        try {
            InputStream _in = FileUtil.init().getConfigFile(_filename);
            Workbook workbook = OfficeUtil.parse(_in,"xlsx");
            Sheet sheet = workbook.getSheet("12月");
            //将12月重命名成需要的月份
            int n = workbook.getSheetIndex(sheet);
            workbook.setSheetName(n, month+"月");

            _in.close();

            Integer userid = 1;
            int rowNum = sheet.getPhysicalNumberOfRows();
            int rowIndex = 0;

            Map<String,CellStyle> styleMap = new HashMap<String,CellStyle>();

            for (int index = 0; index < listclass.size(); index++) {
                Record entry = listclass.get(index);
                rowIndex = 4+index;
                try {
                    boolean flag = true;
                    //信息验证
                    StringBuffer message = new StringBuffer();
                    Row row = sheet.getRow(rowIndex);

                    int cellNum = row.getPhysicalNumberOfCells();
                    //如果这行，一个单元格都没有，认为课程表结束了，不够，需要新加行
                    if (cellNum==0) {//进行表格替换和判断空行，都根据整行数据显示
                        logger.info("rowIndex:"+rowIndex+",cellNum:"+cellNum);
                        //将尾行移动过来
                        sheet.shiftRows( rowIndex, sheet.getLastRowNum(), 1, true, false);
                        cellNum = 1;
                    }
                    row = sheet.getRow(rowIndex)==null?sheet.createRow(rowIndex):sheet.getRow(rowIndex);


                    if (cellNum > 0) {
//       1       2       3  4       5        6
//line5老师	    年	    月	日期	星期	学员姓名	请假类别（生假/师假）	备注（补生假/补师假）	师生比（团体班）
//                                                                  课程模式/10	时数/11	家长签名/12	课时费/13 欠课/14
//line6方方老师	2019	12	1	   周日	    高子涵	         		     周末个	1   		        550
//line7方方老师	2019	12			        霖霖				         周末个	2	    	        1100

                        //studentname、date、weekday、weight、class_status（课程状态0正常-1生假-2师假）
                        String  studentname= entry.get("studentname");
                        int iweekday = entry.getInt("weekday");
                        int iclass_status = entry.getInt("class_status");
                        String class_status = "";
                        String _islost = "";
                        if(iclass_status>0){
                            _islost="自行填写:是/否";
                            switch (iclass_status){
                                case 1:
                                    class_status="生假";break;
                                case 2:
                                    class_status="师假";break;
                                default:
                                    class_status="其他";break;
                            }
                        }
                        Double weight = entry.getDouble("weight");
                        Date date = entry.getDate("date");
                        int day = TimeUtil.getPassDayOfMonth(date);
                        String weekday = TimeUtil.getWeek(iweekday);
                        String classtype = "平个";
                        Double _everclassfee = classfee*weight;
                        if("周日".equals(weekday) || "周六".equals(weekday)){
                            classtype = "周末个";
                            _everclassfee = (classfee+50)*weight;
                        }

                        //getRealCell获取单元格
                        // 设置样式(styleMap:从第4行将样式放入map中，按照列循环设置到cell中)
                        getRealCell(row,0,styleMap).setCellValue(_tearchname);//年
                        getRealCell(row,1,styleMap).setCellValue(year);//年
                        getRealCell(row,2,styleMap).setCellValue(month);//月
                        getRealCell(row,3,styleMap).setCellValue(day);//日
                        getRealCell(row,4,styleMap).setCellValue(weekday);//星期
                        getRealCell(row,5,styleMap).setCellValue(studentname);//学生
                        getRealCell(row,6,styleMap).setCellValue(class_status);//请假

                        getRealCell(row,9,styleMap).setCellValue(classtype);//课程类型
                        getRealCell(row,10,styleMap).setCellValue(weight);//节数
                        getRealCell(row,12,styleMap).setCellValue(_everclassfee);//金额
                        getRealCell(row,13,styleMap).setCellValue(_islost);//欠课


                    }
                    if(rowIndex%100 == 0){
                        Thread.sleep(1000);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    _in.close();
                }

            }

            OfficeUtil.addRow(sheet,++rowIndex);//先空一行
            Row totalRow = OfficeUtil.addRow(sheet,++rowIndex);
            //预计:{{classinfo.all}}　　已上:{{classinfo.done}}　　待上:{{classinfo.will}}
            //其中 一对一:{{classinfo.ydy}}　　秋季班:{{classinfo.qjb}}　　团体班:{{classinfo.ttb}}
            //师假:{{classinfo.teacleave}}　　生假:{{classinfo.studleave}}
            //小程序 list.js :
            // {key:'done',name:'已上'},{key:'will',name:'待上'},{key:'ydy',name:'一对一'},{key:'qjb',name:'秋季班'},
            // {key:'ttb',name:'团体班'},{key:'teacleave',name:'师假'},{key:'studleave',name:'生假'}
            int totalcell = 0;
            for(String key :ParamType.getClassTotalType().keySet()){
                Double val = totalResult.getDouble(key);
                Double valjia = NumberTool.safeToDouble(totalResult.getDouble(key+"jia"),0d);
                if(key.equals("will") || 0d == val ){
                   continue;
                }
                getRealCell(totalRow,totalcell++,styleMap).setCellValue(ParamType.getClassTotalType().get(key)+":平个");//说明
                getRealCell(totalRow,totalcell++,styleMap).setCellValue(val-valjia);// 总-加个 = 平个
                if(!key.equals("done")){
                    getRealCell(totalRow, totalcell++, styleMap).setCellValue("加个");//加个
                    getRealCell(totalRow, totalcell++, styleMap).setCellValue(valjia);//加个
                }
            }


//            rowIndex
            Row row = sheet.getRow(++rowIndex);
//            将模板中多的行删掉
            while(row != null && row.getPhysicalNumberOfCells() > 0){
                Cell cell1 = row.getCell(0);
                String firstCell  = OfficeUtil.getCellValue(cell1);
                if("".equals(firstCell.trim())){
                    break;
                }
                if(firstCell.contains(_tearchname)){
                    OfficeUtil.removeRow(sheet,rowIndex);
                    row = sheet.getRow(rowIndex);
                }else {
                    row = sheet.getRow(rowIndex+1);
                }
            }

            /**
             * todo 以下内容：
             * 处理欠课表（新增字段 欠课编号，补课编号） 2020年1月21日17:02:58
             * 课程类型，互动评估...
             * 导出汇总信息
             * 导出 家长签到表
             */

            String tempPath = FileUtil.getTempDir();
            File file = new File(tempPath);
            if(!file.exists()){
                file.mkdirs();
            }
            _filename = getRelaFileName(_filename,param);

            FileOutputStream excelFileOutPutStream = new FileOutputStream(tempPath+File.separator+_filename);

            // 将最新的 Excel 文件写入到文件输出流中，更新文件信息！
            workbook.write(excelFileOutPutStream);
            // 执行 flush 操作， 将缓存区内的信息更新到文件上
            excelFileOutPutStream.flush();
            // 使用后，及时关闭这个输出流对象， 好习惯，再强调一遍！
            excelFileOutPutStream.close();

            logger.info("out file:"+tempPath+File.separator+_filename);
            return tempPath+File.separator+_filename;

        }catch (Exception e){
            e.printStackTrace();
        }
        return "";

    }

    public String exportPayExcel(List<Record> listclass,Map<String,String> param){
        String _filename = "YY--員工薪資條XX的MM月_TT.xls";

        String tempPath = FileUtil.getTempDir();
        return tempPath+_filename;
    }

    /**
     * 获取替换后的名称
     * @param filename
     * @param param tearchname XX，year YY,month MM
     * @return
     */
    public String getRelaFileName(String filename,Map<String,String> param){
        String _realname = filename;
        if(filename.contains("XX")){
            _realname = _realname.replace("XX", StringUtil.valueOf(param.get("tearchname")));
        }
        if(filename.contains("YY")){
            _realname = _realname.replace("YY", StringUtil.valueOf(param.get("year")));
        }
        if(filename.contains("MM")){
            _realname = _realname.replace("MM", StringUtil.valueOf(param.get("month")));
        }
        if(filename.contains("TT")){
            _realname = _realname.replace("TT",TimeUtil.getUnionkeyDateTime());
        }

        return _realname;
    }

    public  CellStyle defaultCellStyle = null;

    public Cell getRealCell(Row row,int cellnum,Map<String,CellStyle> styleMap){
        Cell cell2 = row.getCell(cellnum);
        int rownum = row.getRowNum();

        if(cell2 ==null){
            cell2 = row.createCell(cellnum);
            logger.info("rownum:"+rownum+",create cell："+cellnum);
        }
        //从第四行开始复制样式
        int cellindex = cell2.getColumnIndex();
        if(rownum == 4){
            styleMap.put("cellstype"+cellindex,cell2.getCellStyle());
            if(defaultCellStyle ==null){
                defaultCellStyle = cell2.getCellStyle();
            }
        }else {
            CellStyle CellStyle = styleMap.get("cellstype"+cellindex);
            //这里可以使用 style1.cloneStyleFrom(cell1.getCellStyle()); 可以防止样式单独修改，目前没用到
            if(CellStyle == null && defaultCellStyle != null){
                CellStyle = defaultCellStyle;
            }
            cell2.setCellStyle(CellStyle);
        }

        return cell2;
    }



}
